package com.zzxx.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zzxx.entity.*;

import com.zzxx.exceptions.UpdateException;
import com.zzxx.mapper.GymMapper;
import com.zzxx.mapper.ManagerMapper;
import com.zzxx.mapper.ManagerPowerMapper;
import com.zzxx.mapper.TicketMapper;
import com.zzxx.service.GymService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class GymServiceImpl implements GymService {
    @Autowired
    private GymMapper gymMapper;
    @Autowired
    private ManagerMapper managerMapper;
    @Autowired(required = false)
    private HttpServletRequest request;
    @Autowired
    private ManagerPowerMapper managerPowerMapper;
    @Autowired
    private TicketMapper ticketMapper;

    @Override
    public PageInfo<Gym> queryAll(Integer start, Integer pageSize) {
        PageHelper.startPage(start,pageSize);
        List<Gym> list=gymMapper.findAll();
        PageInfo<Gym> pageInfo=new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public Gym queryById(String id) {
        return gymMapper.selectByPrimaryKey(id);
    }

    @Override
    public PageInfo<Gym> findPage(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        GymExample gymExample = new GymExample();
        List<Gym> list = gymMapper.selectByExample(gymExample);
        PageInfo<Gym> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public Gym findById(String gid) {
        Gym gym = gymMapper.selectByPrimaryKey(gid);
        return gym;
    }

    @Override
    public void updateById(MultipartFile uploadPic, Gym gym, Manager loginManager) throws IOException, UpdateException {
        //查看是否有权限更改
        ManagerPowerExample example = new ManagerPowerExample();
        example.createCriteria().andManageridEqualTo(loginManager.getId()).andPoweridEqualTo(gym.getId()).andPowerlevelGreaterThanOrEqualTo(3);
        List<ManagerPower> managerPowers = managerPowerMapper.selectByExample(example);
        if (managerPowers.size()!=1) throw new UpdateException("noPower");
        //有图片更改时保存图片
        if (uploadPic!=null){
            String originalFilename = uploadPic.getOriginalFilename();
            //获取后缀
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            //如果后缀时.jpg或者.png才解析，否则返回
            if (!".jpg".equals(suffix)&&!".png".equals(suffix)) throw new UpdateException("noPic");
            //生成保存目录
            String parent = request.getServletContext().getRealPath("work\\gymPic")+"\\"+new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            String newImageName = UUID.randomUUID().toString().replaceAll("-","")+suffix;
            File gymImageFile = new File(parent, newImageName);
            if (!gymImageFile.getParentFile().exists()) {
                gymImageFile.getParentFile().mkdirs();
            }
            uploadPic.transferTo(gymImageFile);
            //保存src
            String src = "\\"+gymImageFile.getAbsolutePath().substring(gymImageFile.getAbsolutePath().lastIndexOf("work"));
            gym.setSrc(src);
        }
        //保存修改信息
        gymMapper.updateByPrimaryKey(gym);
    }

    @Override
    public void addGym(MultipartFile uploadPic, Gym gym) throws IOException, UpdateException {
        //保存图片
        String originalFilename = uploadPic.getOriginalFilename();
        //获取后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //如果后缀时.jpg或者.png才解析，否则返回
        if (!".jpg".equals(suffix)&&!".png".equals(suffix)) throw new UpdateException("noPic");
        //生成保存目录
        String parent = request.getServletContext().getRealPath("work\\gymPic")+"\\"+new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String newImageName = UUID.randomUUID().toString().replaceAll("-","")+suffix;
        File gymImageFile = new File(parent, newImageName);
        if (!gymImageFile.getParentFile().exists()) {
            gymImageFile.getParentFile().mkdirs();
        }
        uploadPic.transferTo(gymImageFile);
        //保存src
        String src = "\\"+gymImageFile.getAbsolutePath().substring(gymImageFile.getAbsolutePath().lastIndexOf("work"));
        gym.setSrc(src);

        gym.setId(UUID.randomUUID().toString().replaceAll("-",""));
        //保存场馆
        gymMapper.insert(gym);
        //生成权限信息
        ManagerPower managerPower = new ManagerPower();
        managerPower.setId(UUID.randomUUID().toString().replaceAll("-",""));
        managerPower.setManagerid(gym.getPrincipalid());
        managerPower.setPowertype(0);
        managerPower.setPowerid(gym.getId());
        managerPower.setPowerlevel(3);
        //保存权限信息
        managerPowerMapper.insert(managerPower);
    }

    @Override
    public void delete(String gid, String mid) throws UpdateException {
        //查看有无权限
        ManagerPowerExample powerExample = new ManagerPowerExample();
        powerExample.createCriteria().andPowertypeEqualTo(0).andPoweridEqualTo(gid).andManageridEqualTo(mid).andPowerlevelGreaterThanOrEqualTo(3);
        List<ManagerPower> managerPowers = managerPowerMapper.selectByExample(powerExample);
        if (managerPowers.size()==0) throw new UpdateException("noPower");
        //删除场馆
        gymMapper.deleteByPrimaryKey(gid);
        //删除票
        TicketExample ticketExample = new TicketExample();
        ticketExample.createCriteria().andTargetidEqualTo(gid);
        ticketMapper.deleteByExample(ticketExample);
        //删除权限信息
        ManagerPowerExample powerExample1 = new ManagerPowerExample();
        powerExample1.createCriteria().andPoweridEqualTo(gid);
        managerPowerMapper.deleteByExample(powerExample1);

    }

    @Override
    public boolean checkPower(String gid, String mid) {
        ManagerPowerExample example = new ManagerPowerExample();
        example.createCriteria().andManageridEqualTo(mid).andPoweridEqualTo(gid).andPowerlevelGreaterThanOrEqualTo(3);
        List<ManagerPower> managerPowers = managerPowerMapper.selectByExample(example);
        return managerPowers.size()==1;
    }

    @Override
    public List<ManagerPower> findPower(String gid, String id) {
        ManagerPowerExample example = new ManagerPowerExample();
        example.createCriteria().andPoweridEqualTo(gid).andManageridNotEqualTo(id);
        List<ManagerPower> list = managerPowerMapper.selectByExample(example);
        return list;
    }

    @Override
    public List<ManagerAndPower> packageMap(List<ManagerPower> list) {
        List<ManagerAndPower> mapList = new ArrayList<>();
        list.forEach(n->{
            ManagerAndPower managerAndPower = new ManagerAndPower();
            managerAndPower.setManagerPower(n);
            String managerid = n.getManagerid();
            Manager manager = managerMapper.selectByPrimaryKey(managerid);
            managerAndPower.setManager(manager);
            mapList.add(managerAndPower);
        });
        return mapList;
    }

    @Override
    public void updatePower(List<ManagerAndPower> list) {
        list.forEach(n->{
            ManagerPower managerPower = n.getManagerPower();
            managerPowerMapper.updateByPrimaryKey(managerPower);
        });
    }

    @Override
    public void removePower(String mpid) {
        managerPowerMapper.deleteByPrimaryKey(mpid);
    }

    @Override
    public String addPower(String addName, String addPower, String addType, String addPowerId) {
        try{
            //先查看有没有这个人
            ManagerExample managerExample = new ManagerExample();
            managerExample.createCriteria().andManagernameEqualTo(addName);
            List<Manager> managers = managerMapper.selectByExample(managerExample);
            if (managers.size()!=1) return "查无此人";
            //看看这个人是不是已经有权限
            Manager manager = managers.get(0);
            ManagerPowerExample powerExample = new ManagerPowerExample();
            powerExample.createCriteria().andManageridEqualTo(manager.getId()).andPoweridEqualTo(addPowerId);
            List<ManagerPower> managerPowers = managerPowerMapper.selectByExample(powerExample);
            if (managerPowers.size()!=0) return "授权失败，该用户已有权限";
            //没问题的话插入
            ManagerPower managerPower = new ManagerPower();
            managerPower.setId(UUID.randomUUID().toString().replaceAll("-",""));
            managerPower.setPowertype(Integer.parseInt(addType));
            managerPower.setPowerlevel(Integer.parseInt(addPower));
            managerPower.setManagerid(manager.getId());
            managerPower.setPowerid(addPowerId);
            managerPowerMapper.insert(managerPower);
            return "success";
        }catch (Exception e){
            return "授权失败";
        }
    }
}
